dojo.provide("slipstream.form.CheckedMultiSelect");
dojo.require("dojox.form.CheckedMultiSelect");
/**
 * @author jaanush
 */
dojo.declare("slipstream.form.CheckedMultiSelect", dojox.form.CheckedMultiSelect, {
	store: null,
	valueName: "",
	labelName: "",

	loadStore: function() {
		//this.store._forceLoad();
		console.debug('load mc store');
		var self=this;
		
		this.store.fetch({
			//onItem: dojo.hitch(console, "debug")
			onComplete: function(items, reqest){
				var result=[];
				dojo.forEach(items,function(item){
					result.push({
						value: (self.valueName?self.store.getValue(item,self.valueName):self.store.getIdentity(item)),
						label: (self.labelName?self.store.getValue(item,self.labelName):self.store.getLabel(item))
					});
					//console.debug(this.store.getIdentity(item));
				},self);
				self.addOption(result);
				//console.debug(result);
			}//dojo.hitch(this, 'addOption')
		});
	},
	/*
	setSelected: function(value){
		//console.debug(value);
		//console.debug(this.options);
		this._setValueAttr(value,false);
		//dojo.forEach(this.objects,function(i){i.selected=false});
		//dojo.forEach(this.getOptions(value),function(i){i.selected=true});
		this._updateSelection();
		dojo.forEach(this.options, function(i){
			i.selected = !i.selected;
		});
		//this.getOptions(value)
		//console.debug(this.getValue);
		//console.debug(this.options);
	},
	*/
	_onNewItem: function(item){
		var self=this;
		//var store = this.store;
		this.addOption({
			value: (self.valueName?self.store.getValue(item,self.valueName):self.store.getIdentity(item)),
			label: (self.labelName?self.store.getValue(item,self.labelName):self.store.getLabel(item))
		});
	},
	
	_onDeleteItem: function(item){
		var self=this;
		//var store = this.store;
		this.removeOption((self.valueName?self.store.getValue(item,self.valueName):self.store.getIdentity(item))+'');
	},
	
	_onSetItem: function(item){
		var self=this;
		//var store = this.store;
		this.updateOption({
			value: (self.valueName?self.store.getValue(item,self.valueName):self.store.getIdentity(item)),
			label: (self.labelName?self.store.getValue(item,self.labelName):self.store.getLabel(item))
		})
	},
	
	postCreate: function(){
		this.inherited(arguments);
		if(this.store && this.store.getFeatures()["dojo.data.api.Notification"]){
			var store = this.store;
			this.connect(store, "onNew", "_onNewItem");
			this.connect(store, "onDelete", "_onDeleteItem");
			this.connect(store, "onSet", "_onSetItem");
		}
	},

	startup: function(){
		this.inherited(arguments);
		if(this.store){
			this.loadStore();
		}
	}
});